<template>
  <div class="movie-list-container">
    <div class="header">
      <h1 class="text-2xl font-bold mb-4">商品列表</h1>
      <div class="search-filter">
        <div class="search-box relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center">
            <i class="fa fa-search text-gray-400"></i>
          </div>
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索商品..." 
            @input="debounceSearch"
            class="px-10 py-2 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:shadow-sm w-full"
          >
        </div>
      </div>
    </div>
    
    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
      <div v-if="loading" class="col-span-full flex justify-center items-center py-10">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
      
      <div v-else-if="filteredMovies.length === 0" class="col-span-full text-center py-10">
        <p class="text-gray-500">没有找到匹配的商品</p>
      </div>
      
      <MovieCard 
        v-else 
        v-for="movie in paginatedMovies" 
        :key="movie.id" 
        :movie="movie"
        @view-movie="handleViewMovie"
        @play-movie="handlePlayMovie"
        class="group"
      />
    </div>

    <!-- 清除浮动 -->
    <div class="clear-float" style="clear: both;"></div>

    <!-- 分页按钮移到商品列表下方 -->
    <div v-if="totalPages > 1" class="pagination flex justify-center mt-6">
      <button 
        @click="currentPage--" 
        :disabled="currentPage === 1" 
        class="px-4 py-2 bg-blue-500 text-white rounded-l hover:bg-blue-600"
      >
        <i class="fa fa-chevron-left"><</i>
      </button>
      <span class="px-4 py-2 bg-gray-200 rounded">{{ currentPage }} / {{ totalPages }}</span>
      <button 
        @click="currentPage++" 
        :disabled="currentPage === totalPages" 
        class="px-4 py-2 bg-blue-500 text-white rounded-r hover:bg-blue-600"
      >
        <i class="fa fa-chevron-right">></i>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import apiService from '@/services/api';
import MovieCard from '@/components/common/MovieCard.vue';

const router = useRouter();
const route = useRoute();
const searchQuery = ref('');
const movies = ref([]);
const loading = ref(true);
const error = ref('');
const currentPage = ref(1);
const itemsPerPage = 12; // 每页显示12个商品，对应4行

// 防抖搜索
const debounceTimeout = ref(null);
const debounceSearch = () => {
  if (debounceTimeout.value) {
    clearTimeout(debounceTimeout.value);
  }
  debounceTimeout.value = setTimeout(() => {
    currentPage.value = 1;
    if (searchQuery.value.trim()) {
      fetchMovies();
    }
  }, 300);
};

// 获取电影列表
const fetchMovies = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await apiService.getAllItems();
    movies.value = response;
    console.log(movies);
  } catch (err) {
    error.value = '获取商品列表失败，请稍后重试';
    console.error('获取商品列表失败:', err);
  } finally {
    loading.value = false;
  }
};

// 过滤电影列表
const filteredMovies = computed(() => {
  if (!searchQuery.value.trim()) return movies.value;
  
  const query = searchQuery.value.toLowerCase();
  return movies.value.filter(movie => 
    movie.title.toLowerCase().includes(query) || 
    movie.desc.toLowerCase().includes(query)
  );
});

// 分页电影列表
const paginatedMovies = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return filteredMovies.value.slice(start, end);
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredMovies.value.length / itemsPerPage);
});

// 查看电影详情
const handleViewMovie = (movieId) => {
  router.push(`/movie/${movieId}`);
};

// 播放电影
const handlePlayMovie = (playUrl) => {
  console.log('播放电影:', playUrl);
  // 这里可以添加播放逻辑
  // window.open(playUrl, '_blank');
};

// 初始加载
onMounted(fetchMovies);

// 监听路由变化
watch(
  () => route.query,
  (newQuery, oldQuery) => {
    console.log('路由变化:', newQuery, oldQuery);
    fetchMovies();
  }
);
</script>

<style scoped>
.movie-list-container {
  padding: 20px;
}

.header {
  margin-bottom: 30px;
  text-align: center;
}

.search-filter {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.search-box {
  flex: 1;
  display: flex;
  position: relative;
  max-width: 400px;
  width: 100%;
}

.search-box input {
  padding-left: 40px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 20px;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
  transition: border-color 0.3s;
  margin: 0 auto;
}

.search-box input:focus {
  border-color: #007bff;
}

@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
  }
  
  .search-box {
    max-width: 100%;
  }
}

.group {
  margin: 20px;
  float: left;
  width: 300px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.group:hover {
  transform: translateY(-5px);
}

.pagination {
  gap: 10px;
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination button:hover {
  background-color: #0056b3;
}

.pagination button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.pagination span {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  background-color: #f1f1f1;
  color: #333;
  border-radius: 4px;
}
</style>